package com.qyhl.webtv.module_microvideo.shortvideo.rank;

import android.Manifest;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.microvideo.ShortVideoBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.GridDividerItemDecoration;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 排行榜
 */
@Route(path = ARouterPathConstant.SHORT_VIDEO_RANK)
public class ShortVideoRankActivity extends BaseActivity implements ShortVideoRankContract.ShortVideoRankView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.bottom_bar)
    RelativeLayout bottomBar;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "type")
    int type;//7 总榜   6 周榜

    @Autowired(name = "id")
    String activityId;

    private CommonAdapter commonAdapter;

    private int page = 1;//分页

    private ShortVideoRankPresenter mPresenter;

    private List<ShortVideoBean> mDataList = new ArrayList<>();

    private BottomBarStatus bottomBarStatus = BottomBarStatus.EXPAND;

    private boolean isRunning = false;

    private enum BottomBarStatus {
        EXPAND,
        COLLAPSED
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.micro_activity_short_video_rank;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ShortVideoRankPresenter(this);
        initView();
    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.getDataList(type, activityId, page + "");
    }

    private void initView() {
        if (type == 7) {
            title.setText("总榜");
        } else {
            title.setText("周榜");
        }

        loadMask.setStatus(LoadingLayout.Loading);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new GridLayoutManager(this, 2));
        recycleView.addItemDecoration(new GridDividerItemDecoration(4, getResources().getColor(R.color.micro_short_video_bg)));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<ShortVideoBean>(this, R.layout.micro_item_short_video_home, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShortVideoBean bean, int position) {
                holder.setText(R.id.summary, bean.getTitle());
                holder.setText(R.id.user_nickname, bean.getUserNickName());
                holder.setText(R.id.hot_value, bean.getScore() + "");
                holder.setText(R.id.tagName, bean.getTagName());
                ImageView tag = holder.getView(R.id.rank_tag);
                if (type == 6) {
                    switch (bean.getwRanking()) {
                        case 1:
                            tag.setImageResource(R.drawable.short_video_week_rank_top1);
                            break;
                        case 2:
                            tag.setImageResource(R.drawable.short_video_week_rank_top2);
                            break;
                        case 3:
                            tag.setImageResource(R.drawable.short_video_week_rank_top3);
                            break;
                        default:
                            break;
                    }
                } else {
                    switch (bean.getmRanking()) {
                        case 1:
                            tag.setImageResource(R.drawable.short_video_total_rank_top1);
                            break;
                        case 2:
                            tag.setImageResource(R.drawable.short_video_total_rank_top2);
                            break;
                        case 3:
                            tag.setImageResource(R.drawable.short_video_total_rank_top3);
                            break;
                        default:
                            break;
                    }
                }


                ImageView cover = holder.getView(R.id.cover);
                Glide.with(ShortVideoRankActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_large_default).error(R.drawable.cover_large_default))
                        .into(cover);

                RoundedImageView headIcon = holder.getView(R.id.user_avatar);
                Glide.with(ShortVideoRankActivity.this)
                        .load(bean.getUserLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                        .into(headIcon);

            }
        });
    }

    private void setListeners() {
        refresh.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getDataList(type, activityId, page + "");
        });

        refresh.setOnLoadMoreListener(refreshLayout -> mPresenter.getDataList(type, activityId, page + ""));

        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            page = 1;
            mPresenter.getDataList(type, activityId, page + "");
        });

        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                showHideBottombar(dy);
            }
        });


        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", (Serializable) mDataList);
                bundle.putString("actId", activityId);
                bundle.putInt("position", position);
                bundle.putInt("page", page);
                bundle.putInt("type", type);
                RouterManager.router(ARouterPathConstant.SHORT_VIDEO_PLAY,bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @OnClick({R2.id.back_btn, R2.id.search_btn, R2.id.shoot_btn})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.back_btn) {
            finish();
        } else if (i == R.id.search_btn) {
            Bundle bundle = new Bundle();
            bundle.putString("type", "all");
            bundle.putString("id", activityId);
            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SEARCH);

        } else if (i == R.id.shoot_btn) {
            String activityStatus = CommonUtils.getInstance().getShortVideoState();
            switch (activityStatus) {
                case "BEGINNING":
                    MPermissionUtils.requestPermissionsResult(ShortVideoRankActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO}, new MPermissionUtils.OnPermissionListener() {
                        @Override
                        public void onPermissionGranted() {

                            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                                @Override
                                public void login(boolean isLogin) {
                                    if (isLogin) {
                                        if (StringUtils.isMi8()) {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("id", activityId);
                                            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT2);
                                        } else {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("id", activityId);
                                            RouterManager.router(ARouterPathConstant.SHORT_VIDEO_SHOOT);
                                        }
                                    } else {
                                        Toasty.normal(ShortVideoRankActivity.this, "尚未登录或登录已失效！").show();
                                        RouterManager.routerLogin(ShortVideoRankActivity.this, 0);
                                    }
                                }

                                @Override
                                public void error(String s) {

                                }
                            });

                        }

                        @Override
                        public void onPermissionDenied() {
                            MPermissionUtils.showTipsDialog(ShortVideoRankActivity.this);
                        }
                    });
                    break;
                case "END":
                    showToast("活动已结束！", 4);
                    break;
                default:
                    showToast("活动未开始！", 4);
                    break;
            }
        }
    }

    @Override
    public void setData(List<ShortVideoBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        page++;
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setErrorText(msg);
            if (msg.contains("网络")) {
                loadMask.setErrorImage(R.drawable.error_network);
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
            }
        }
    }


    /**
     * 通过滑动距离判断上滑还是下滑来展开收起拍摄按钮
     *
     * @param dy 滑动
     */
    public void showHideBottombar(int dy) {
        if (!isRunning) {
            if (dy > 10) {  //上滑
                if (bottomBarStatus == BottomBarStatus.EXPAND) {
                    bottomBarStatus = BottomBarStatus.COLLAPSED;
                    //执行收起
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, 70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            } else if (dy < -10) { //下拉
                if (bottomBarStatus == BottomBarStatus.COLLAPSED) {
                    bottomBarStatus = BottomBarStatus.EXPAND;
                    //执行展开
                    ViewCompat.animate(bottomBar)
                            .translationYBy(StringUtils.dip2px(this, -70))
                            .setDuration(300)
                            .setListener(new ViewPropertyAnimatorListener() {
                                @Override
                                public void onAnimationStart(View view) {
                                    isRunning = true;
                                }

                                @Override
                                public void onAnimationEnd(View view) {
                                    isRunning = false;
                                }

                                @Override
                                public void onAnimationCancel(View view) {

                                }
                            });
                }
            }
        }
    }

}
